package com.leantech.android.browser.ui.browser.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.db.entity.ShortCutEntryEntity
import com.cscj.android.repository.network.Result
import com.cscj.android.repository.repo.shortcut.ShortCutRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class ShortCutEntryViewModel : ViewModel(), KoinComponent {

    private val shortCutRepository by inject<ShortCutRepository>()

    init {
        viewModelScope.launch {
            shortCutRepository.loadShortCutEntries()
        }
    }

    val localShortCutEntryFlow = shortCutRepository.localShortCutEntriesFlow()
        .map { list ->
            list.distinctBy {
                when (it.type) {
                    ShortCutEntryEntity.EntryTypeShortCut -> it.id.toString()
                    ShortCutEntryEntity.EntryTypeHistory -> if (it.isRoot) it.id.toString() else it.link
                    ShortCutEntryEntity.EntryTypeFavorites -> if (it.isRoot) it.id.toString() else it.link
                    else -> null
                }
            }
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )

    suspend fun removeShortCutEntry(entry: ShortCutEntryEntity): Result<Unit> {
        return withContext(Dispatchers.IO) {
            shortCutRepository.deleteShortCutEntry(entry.id)
        }
    }

}